var amqp = require('amqplib');

class Queue {
  constructor(amqp_address,queue_name,queue_max_count) {
    this.queue_name = queue_name
    this.queue_max_count = queue_max_count
    this.amqp_address = amqp_address
  }

  async connect() {
    this.conn = await amqp.connect(this.amqp_address)
    this.channel = await this.conn.createChannel()
    this.channel.assertQueue(this.queue_name, {durable: false});
  }

  async put(msg) {
//    while (true){
//      let aq = await this.channel.checkQueue(this.queue_name)
//      if (aq.messageCount < this.queue_max_count){
        this.channel.sendToQueue(this.queue_name, Buffer.from(msg));
//        return
//      }else {
//        await sleep(5000)
//      }
//    }
  }

  async get() {
    while (true){
      let msg = await this.channel.get(this.queue_name,{noAck:true})
      if (msg)
        return msg.content.toString()
      else
        await sleep(5000)
    }
  }

  async close(){
    await this.conn.close()
  }
}

async function sleep(timeout) {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      resolve();
    }, timeout);
  });
}

class IPSchedu{
  constructor(dns_ips) {
    this.queue = []
    this.data = {}
    for (let i in dns_ips){
      this.data[dns_ips[i]] = {
        time_spand:[0,0,0,0,0,0,0,0,0,0,10],
        time_average: function(){return this.time_spand.reduce((total,current)=>{return total+=current})/this.time_spand.length}
      }
    }
  }

  queue_check(){
    if (this.queue.length < 5){
      for (let key in this.data){
        let loop_range = Math.ceil(10/Math.pow(this.data[key].time_average(),2))
        for (let i=0;i<loop_range;i++){
          this.queue.unshift(key)
        }
      }
      this.queue.sort(function(){ return 0.5 - Math.random() })
    }
  }

  feedback(ip,time_spand){
      this.data[ip]['time_spand'].unshift(time_spand)
      this.data[ip]['time_spand'].pop()
  }
  get(){
    this.queue_check()
    return this.queue.pop()
  }
}

module.exports={ Queue,sleep,IPSchedu}
